﻿namespace TwlPhy
{
    using System;
    /// <summary>
    ///物理系统不与Unity耦合 
    /// </summary>
    public class Physics2D
    {
        static public int logicFrameNum = 20;
        static public float logicFrame = logicFrameNum / 1000f;
        static public int syncIntervalFrame = 3;//10帧同步一次位置

        #region 碰撞检测算法
        /// <summary>
        /// 碰撞检测核心
        /// </summary>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        /// <returns></returns>
        static public bool isCollision(Box2D p1, Box2D p2)
        {
            return !(p2.Top <= p1.Bottom || p2.Bottom >= p1.Top || p2.Left >= p1.Right || p2.Right <= p1.Left);
        }
        #endregion

        #region 碰撞接口提供
        //盒子碰撞
        static public bool isCollision(Box2D box)
        {
            return LevelMgr.Instance.NowLevel.isCollision(box);
        }
        //盒子碰撞
        static public bool isCollision(DymicBox2D dyBox, Box2D box, Vector2 dir, ref float len)
        {
            return LevelMgr.Instance.NowLevel.isCollision(dyBox, box, dir, ref len);
        }
        //射线碰撞
        static public bool rayCast(Vector2 start, Vector2 dir, float len)
        {
            return LevelMgr.Instance.NowLevel.rayCast(start, dir, len);
        }
        //提供玩家移动碰撞检测
        static public bool moveCast(DymicBox3D dyBox, Vector2 dir, float len, ref float vaildLen)
        {
            //左右移动 起点: 移动盒最高 最低
            vaildLen = len;
            Box2D box2d = null;
            if (dir.y != 0)
            {
                //float addY = dir.y < 0 ? 0 : dyBox.width;
                //float y = len / 2 * dir.y + dyBox.centerY + addY;
                float boxLen = len <= dyBox.width ? dyBox.width : len;
                box2d = new Box2D(dyBox.centerX, dyBox.centerY + len / 2 * dir.y, dyBox.length, boxLen);
            }
            else
            {
                float boxLen = len <= dyBox.length ? dyBox.length : len;
                box2d = new Box2D(dyBox.centerX + len / 2 * dir.x, dyBox.centerY, boxLen, dyBox.width);
            }
            bool isCol = isCollision(dyBox, box2d, dir, ref vaildLen);
            vaildLen = vaildLen > len ? len : vaildLen;
            return isCol;
        }
        #endregion
    }

    public class Physics3D
    {
        static public bool isCollision(DymicBox3D p1, DymicBox3D p2)
        {
           return !(p2.Top <= p1.Bottom || p2.Bottom >= p1.Top || p2.Left >= p1.Right || p2.Right <= p1.Left || p2.MaxH <= p1.MinH || p2.MinH >= p1.MaxH);
        }
    }
}